package com.example.administrator.easycure.activities;

import android.Manifest;
import android.animation.Animator;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.example.administrator.easycure.R;

import java.util.ArrayList;
import java.util.List;

public class LocationActivity extends AppCompatActivity {

    //我两个地图实现到定位到我的位置了，配置的话就theme不动，
    // 然后方法我都注视了，也是不动就行；动画就是一个空间，几个变量，几个方法还有一个theme

    //地图用变量
    public LocationClient mLocationClient;
    private MapView activity_location_bmv;
    private BaiduMap baiduMap;
    private boolean isFirstLocate = true;

    //onCreate中调用揭露动画
    private View content;//根布局对象（用来控制整个布局）
    private View mPuppet;//揭露层对象
    private int mX ;
    private int mY ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        init();
        baiduMap.setMyLocationEnabled(true);
        super.onCreate(savedInstanceState);

        content = findViewById(R.id.activity_location);
        mPuppet = findViewById(R.id.view_puppet);
        mPuppet.bringToFront();

        //动画需要依赖于某个视图才可启动，
        // 这里依赖于根布局对象，并且开辟一个子线程，充分利用资源
        content.post(new Runnable() {
            @Override
            public void run() {
                mX = getIntent().getIntExtra("cx", 0);
                mY = getIntent().getIntExtra("cy", 0);
                Animator animator = createRevealAnimator(mX, mY);
                animator.start();
            }
        });

    }

    public void init(){
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new MyLocationListener());
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_location);
        activity_location_bmv = (MapView) findViewById(R.id.activity_location_bmv);
        baiduMap = activity_location_bmv.getMap();

        requestPermission();
    }

    //动画
    private Animator createRevealAnimator(int x, int y) {
        float startRadius = 0;
        float endRadius = (float) Math.hypot(content.getHeight(), content.getWidth());

        Animator animator = ViewAnimationUtils.createCircularReveal(
                content, x, y,
                startRadius,
                endRadius);
        animator.setDuration(660);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        //判断标志位reversed，true则为添加返回键版动画监听器，false则为跳转动画开启版
        // if (!reversed)
        animator.addListener(animatorListener1);
        return animator;
    }

    //定义动画状态监听器_跳转动画开启版
    private Animator.AnimatorListener animatorListener1 = new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {
//            content.setVisibility(View.VISIBLE);//跳转进来时，（因为finish之前会将之设置为不可见，）
//  ——后期不用了，因为进来的时候会自动绘制所有布局和控件
            // 根布局要设置为可见，与finish部分的不可见相对应
//            mPuppet.setAlpha(1);
        }
        @Override
        public void onAnimationEnd(Animator animation) {
            mPuppet.startAnimation(createAlphaAnimation());
            mPuppet.setVisibility(View.INVISIBLE);//动画结束时，揭露动画设置为不可见

            activity_location_bmv.setVisibility(View.VISIBLE);
        }
        @Override
        public void onAnimationCancel(Animator animation) {
        }
        @Override
        public void onAnimationRepeat(Animator animation) {
        }
    };

    //动画
    private AlphaAnimation createAlphaAnimation() {
        AlphaAnimation aa = new AlphaAnimation(1,0);
        aa.setDuration(400);
        aa.setInterpolator(new AccelerateDecelerateInterpolator());//设置插值器
        return aa;
    }

    //申请列表
    private void requestPermission(){
        //        申请权限
        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(LocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ContextCompat.checkSelfPermission(LocationActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (ContextCompat.checkSelfPermission(LocationActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!permissionList.isEmpty()) {
            String [] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(LocationActivity.this, permissions, 1);
        } else {
            requestLocation();
        }
    }

    //地图
    private void navigateTo(BDLocation location) {
        if (isFirstLocate) {
            Toast.makeText(this, "nav to " + location.getAddrStr(), Toast.LENGTH_SHORT).show();
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.animateMapStatus(update);
            update = MapStatusUpdateFactory.zoomTo(16f);
            baiduMap.animateMapStatus(update);
            isFirstLocate = false;
        }
        MyLocationData.Builder locationBuilder = new MyLocationData.
                Builder();
        locationBuilder.latitude(location.getLatitude());
        locationBuilder.longitude(location.getLongitude());
        MyLocationData locationData = locationBuilder.build();
        baiduMap.setMyLocationData(locationData);
    }
    //地图
    private void requestLocation() {
        initLocation();
        mLocationClient.start();
    }
    //地图
    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setScanSpan(5000);
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
    }
    //地图
    @Override
    protected void onResume() {
        super.onResume();
        activity_location_bmv.onResume();
    }
    //地图
    @Override
    protected void onPause() {
        super.onPause();
        activity_location_bmv.onPause();
    }
    //地图
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        activity_location_bmv.onDestroy();
        baiduMap.setMyLocationEnabled(false);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    for (int result : grantResults) {
                        if (result != PackageManager.PERMISSION_GRANTED) {
                            Toast.makeText(this, "必须同意所有权限才能使用本程序", Toast.LENGTH_SHORT).show();
                            finish();
                            return;
                        }
                    }
                    requestLocation();
                } else {
                    Toast.makeText(this, "发生未知错误", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }
    //地图
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location.getLocType() == BDLocation.TypeGpsLocation
                    || location.getLocType() == BDLocation.TypeNetWorkLocation) {
                navigateTo(location);
            }
        }

    }



//    @Override
//    public void onBackPressed() {
//        //动画需要依赖于某个视图才可启动，
//        // 这里依赖于根布局对象，并且开辟一个子线程，充分利用资源
//        activity_location_bmv.setVisibility(View.INVISIBLE);
//        content.post(new Runnable() {
//            @Override
//            public void run() {
//                mX = getIntent().getIntExtra("cx", 0);
//                mY = getIntent().getIntExtra("cy", 0);
//                Animator animator = createRevealAnimator1(mX, mY);
//                animator.start();
//            }
//        });
//    }

    ////////////////////////////
    private Animator createRevealAnimator1(int x, int y) {
        float startRadius = (float) Math.hypot(content.getHeight(), content.getWidth());
        float endRadius = 0;

        //注意揭露动画开启时是用根布局作为操作对象，关闭时用揭露层作为操作对象
        Animator animator = ViewAnimationUtils.createCircularReveal(
                mPuppet, x, y,
                startRadius,
                endRadius);
        animator.setDuration(500);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());//设置插值器
        animator.addListener(animatorListener0);
        return animator;
    }

    //定义动画状态监听器_按下返回键版
    private Animator.AnimatorListener animatorListener0 = new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {
            mPuppet.setVisibility(View.VISIBLE);//按下返回键时，动画开启，揭露层设置为可见
        }
        @Override
        public void onAnimationEnd(Animator animation) {
            mPuppet.setVisibility(View.INVISIBLE);

            finish();
        }
        @Override
        public void onAnimationCancel(Animator animation) {
        }
        @Override
        public void onAnimationRepeat(Animator animation) {
        }
    };
/////////////////////////////
}
